package org.eminem.hbase;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.HTable;

/**
 * Hbase Client
 */
public class HbaseClient {

    private static Configuration configuration;
    private static Connection conn = null ;
    /**
     * get Configuration instance
     */
    public static synchronized Configuration getConfiguration(String quorum,String clientPort) {
        if (configuration == null) {
            configuration = HBaseConfiguration.create();
            configuration.set("hbase.zookeeper.quorum", quorum);
            configuration.set("hbase.zookeeper.property.clientPort", clientPort);
        }
        return configuration;
    }
    
	public static synchronized Connection getConnection(Configuration conf) throws IOException {
		if(conn == null || conn.isClosed()) {
			conn = ConnectionFactory.createConnection(conf) ;
		}
		return conn;
	}

	public static synchronized HTable getHTable(Configuration conf,HTable table,String tableName) throws Exception {
		if(table == null) {
			conn = getConnection(conf) ;
			table = (HTable) conn.getTable(TableName.valueOf(tableName)) ;
		}
		return table ;
	}
	
	public static void closeHTable(HTable table) throws IOException {
		if(table!=null) {
			table.close();
		}
	}
	
	public static void closeConn() throws IOException {
		if(conn!=null) {
			conn.close();
		}
	}

}
